package com.jintoufs.weixin.scene;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.jintoufs.domain.collect.Collect;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.MessageConstants;
import com.jintoufs.domain.contacts.Contacts;
import com.jintoufs.domain.coupon.Coupon;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.customer.CustomerCoupon;
import com.jintoufs.domain.images.Images;
import com.jintoufs.domain.scene.SceneOrder;
import com.jintoufs.domain.scene.SceneOrderDetail;
import com.jintoufs.domain.scene.SceneTicket;
import com.jintoufs.interceptor.ParamCheck;
import com.jintoufs.service.banner.BannerService;
import com.jintoufs.service.collect.CollectService;
import com.jintoufs.service.contacts.ContactsService;
import com.jintoufs.service.coupon.CouponService;
import com.jintoufs.service.customer.CustomerCouponService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.service.scene.SceneOrderService;
import com.jintoufs.service.scene.SceneService;
import com.jintoufs.service.scene.SceneTicketService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.weixin.SupportAction;
import org.cosmos.modules.exception.ServiceException;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by pengyang on 2017/12/26.
 */
@Scope("prototype")
@RequestMapping("/api")
@RestController
public class ScenesAction extends SupportAction {
    @Resource
    private ContactsService contactsService;
    @Resource
    private SceneService sceneService;
    @Resource
    private SceneTicketService sceneTicketService;
    @Resource
    private CollectService collectService;

    @Resource
    private CustomerService customerService;

    @Resource
    private ImageService imageService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private SceneOrderService sceneOrderService;
    @Resource
    private CouponService couponService;
    @Resource
    CustomerCouponService customerCouponService;

    @GetMapping("/scenes/index")
    public AjaxMsg index(String regionName,Integer pageSize) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Map<String, Object> result = new HashMap<>();
            Map map = new HashMap<>();
            map.put("typeId", Constants.BANNER_TYPE_SCENE);
            map.put("status", Constants.RES_STATUS_NORMAL);
            List<Map<String, Object>> banners = bannerService.queryByParams(map);
            map.put("recommend",Constants.PRODUCT_RECOMMEND);
            map.put("regionName", regionName);
            //获取推荐鱼·定制
            List<Map<String, Object>> scenes = sceneService.getRecommends(map);
            map.put("pageSize", pageSize);
            //获取进店列表 首页第一次加载，默认从第一条数据取
            map.put("pageStart", 0);
            List<Map> sceneAll = sceneService.getBySearch(map);
            result.put("sceneAll", sceneAll);
            result.put("banner", banners);
            result.put("sceneList", scenes);
            ajaxMsg.setDatas(result);
        } catch (Exception e) {
            ajaxMsg.setMessage("error");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }



    /**
     * 根据城市获取鱼·定制列表
     *
     * @param regoinId 城市地址编码
     * @return
     */
    @ParamCheck(params = "regoinId")
    @GetMapping("/scenes/list")
    public AjaxMsg getScenes(String regoinId, Integer pageSize, Integer pageNum) {
        //TODO yangpeng 分页，地址范围
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap<>(1);
        params.put("regoinId", regoinId);
        params.put("status",Constants.RES_STATUS_NORMAL);
        try {
            List<Map<String, Object>> scenes = sceneService.getScenesByParams(params);
            ajaxMsg.setDatas(scenes);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    /**
     * 根据sceneId获取鱼·定制详情,图片集，鱼·定制产品列表，预定须知
     *
     * @param sceneId
     * @return
     */
    @GetMapping(value = "/scenes/{scenenId}")
    public AjaxMsg getScene(@PathVariable("scenenId") String sceneId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> results = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        //鱼·定制id，用于查询鱼·定制产品
        params.put("sceneId", sceneId);
        //所属id，用于查询图片集
        params.put("valueId", sceneId);
        //鱼·定制id，用于查询鱼·定制信息
        params.put("id", sceneId);
        try {
            List<Map<String, Object>> scenes = sceneService.getScenesByParams(params);
            params.remove("id");
            params.put("status",Constants.RES_STATUS_NORMAL);
            List<Map<String, Object>> tickets = sceneService.getTicketsByParams(params);
            List<Images> images = imageService.selectByparams(params);
            List<String> imagesList = new ArrayList<>();
            Map<String, Object> scene = new HashMap<>();
            if (!ValidUtil.isEmpty(scenes)) {
                scene = scenes.get(0);
            }
            List<String> notes = null;
            for (Images image : images) {
                String url = image.getPath();
                imagesList.add(url);
            }
            results.put("images", imagesList);
            if (!imagesList.isEmpty()) {
                results.put("coverImage", imagesList.get(0));
            }
            results.put("tickets", tickets);
            results.put("notes", notes);
            results.put("scene", scene);
            ajaxMsg.setDatas(results);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }


    /**
     * 根据ticketId获取鱼·定制产品详情，图片集，预定须知
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/tickets/detail")
    public AjaxMsg getTickets(String id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap<>(1);
        params.put("id", id);
        try {
            Map<String, Object> ticket = sceneService.getTicketsByParams(params).get(0);
            Map result = new HashMap();
            params.clear();
            params.put("valueId",ticket.get("sceneId"));
            params.put("cover",1);
            Images images = imageService.selectByparams(params).get(0);
            ticket.put("path", images.getPath());
            result.put("ticket", ticket);
            ajaxMsg.setDatas(result);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }


    @GetMapping(value = "/tickets/ticketPrice")
    public AjaxMsg ticketPrice(String id,String startDate) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = new HashMap<>(2);
        params.put("id", id);
        params.put("startTime",startDate);
        Map ticketPrice = new HashMap(3);
        //TODO yangpeng 鱼·定制价格接口
        try {
          /*  List<Map<String, Object>> ticketPrices = sceneService.queryPriceByParams(params);
            ajaxMsg.setDatas(ticketPrices);*/
         List<Map<String,Object>> tickets =sceneTicketService.selectByParams(params);
            if (!ValidUtil.isEmpty(tickets)) {
                Map<String, Object> ticket = tickets.get(0);
                ticketPrice.put("price", ticket.get("price"));
                ticketPrice.put("date", startDate);
                ticketPrice.put("reserve",100);
                ticketPrice.put("retailPrice", ticket.get("orignPrice"));
                List ticketPrices = new ArrayList();
                ticketPrices.add(ticketPrice);
                ajaxMsg.setDatas(ticketPrices);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    /**
     * 收藏一个鱼·定制
     *
     * @param sceneId
     * @param token
     * @return
     */
    @PostMapping(value = "/collect")
    public AjaxMsg collectScene(String sceneId, String token) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Collect collect = new Collect();
            Customer customer = customerService.getByToken(token);
            collect.setCustomerId(customer.getId().toString());
            //TODO yangpeng 收藏，获取收藏类型
            collect.setTypeId(123);
            collect.setValueId(sceneId);
            collect.setAddTime(new Date());
            collect.setId(getUUID());
            collectService.collect(collect);
            //返回保存的收藏
            ajaxMsg.setDatas(collect);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(e.getMessage());
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    /**
     *
     * @param token
     * @param id
     * @param number
     * @param couponId
     * @param userInfo
     * @return
     */
    @ParamCheck(params = "token,id,userInfo,number")
    @GetMapping(value = "tickets/order")
    public AjaxMsg createOrder(String token, String id,String number,
                               String couponId, String userInfo, String remark,String useDate) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        SceneOrder sceneOrder = new SceneOrder();
        Customer customer = getCustomerByToken(token);
        if (!ValidUtil.isEmpty(customer)){
            try {
                List<Map> userList = JSONArray.parseArray(userInfo, Map.class);
                Map user = userList.get(0);
                Contacts contacts = new Contacts();
                contacts.setIdCard(user.get("idCard").toString());
                contacts.setName(user.get("name").toString());
                contacts.setTelephone(user.get("tel").toString());
                contacts.setUserId(customer.getId());
                Map<String,Object> param = new HashMap<>();
                param.put("userId",customer.getId());
                param.put("isDefault",true);
                List<Contacts> contactsList = contactsService.selectByParam(param);
                contacts.setIsDefault(true);
                for (Contacts contacts1:contactsList){
                    if (contacts1.getIsDefault()){
                        contacts.setIsDefault(false);
                    }
                }
                param.clear();
                param.put("idCard",contacts.getIdCard());
                param.put("telephone",contacts.getTelephone());
                param.put("name",contacts.getName());
                contactsList = contactsService.selectByParam(param);
                if (contactsList.isEmpty()){
                    contactsService.save(contacts,getUUID());
                }
                SceneTicket sceneTicket = sceneService.getTicketById(id);
                sceneOrder.setCustomerId(customer.getId());
                if(!ValidUtil.isEmpty(contacts.getIdCard())){
                    sceneOrder.setIdcard(contacts.getIdCard());
                }
                sceneOrder.setRealName(contacts.getName());
                //鱼·定制id可以不用传
                sceneOrder.setSceneId(sceneTicket.getSceneId());
                sceneOrder.setTelephone(contacts.getTelephone());
                //放入状态未支付
                sceneOrder.setStatus(Constants.ORDER_STATUS_UNPAY);
                //订单创建时间
                sceneOrder.setCreateTime(new Date());
                sceneOrder.setModifyTime(new Date());
                sceneOrder.setRemark(remark);
                sceneOrder.setSceneId(sceneTicket.getSceneId());
                sceneOrder.setRecommendId(customer.getRecommendId());
                sceneOrder.setSpreadId(customer.getSpreadId());
                if(!ValidUtil.isEmpty(useDate)){
                    sceneOrder.setUseDate(useDate);
                }
                //验证优惠券
                BigDecimal discount = new BigDecimal(0);
                CustomerCoupon customerCoupon = null;
                if(!ValidUtil.isEmpty(couponId)){
                    param.clear();
                    param.put("customerId",customer.getId());
                    param.put("couponId",couponId);
                    List<CustomerCoupon> customerCoupons = customerCouponService.queryByParam(param);
                    if(customerCoupons !=null && customerCoupons.size()>0){
//                    Integer minReserve = sceneTicketService.getMinReserve(id,useDate);
//                    if (minReserve>Integer.valueOf(number)){
                        customerCoupon = customerCoupons.get(0);
                        if (customerCoupon.getUsedTime()==null){
                            Coupon coupon = couponService.getById(customerCoupon.getCouponId());
                            if(!Constants.COUPON_TYPE_SCENE.equals(coupon.getTypeId())){
                                ajaxMsg.setCode(AjaxMsg.FAILURE);
                                ajaxMsg.setMessage("优惠券类型不匹配！");
                            }
                            Date now = new Date();
                            if(coupon.getSendStartDate().before(now) && coupon.getSendEndDate().after(now)){
                                discount = coupon.getMaxAmount();
                            }else{
                                ajaxMsg.setCode(AjaxMsg.FAILURE);
                                ajaxMsg.setMessage("优惠券当前不可用！");
                            }
                        }else{
                            ajaxMsg.setCode(AjaxMsg.FAILURE);
                            ajaxMsg.setMessage("该优惠券已经使用过，不能重复使用！");
                        }
//                    }else {
//                        ajaxMsg.setCode(AjaxMsg.FAILURE);
//                        ajaxMsg.setMessage("当前没有该鱼·定制产品或该鱼·定制产品数据出错。");
//                    }


                    }else{
                        ajaxMsg.setCode(AjaxMsg.FAILURE);
                        ajaxMsg.setMessage("该优惠券不存在或者不在使用期限内！");
                    }
                }
                //订单优惠价
                sceneOrder.setPrice(sceneTicket.getPrice().multiply(new BigDecimal(number)).subtract(discount));
                //订单原价
                sceneOrder.setActPrice(sceneTicket.getPrice().multiply(new BigDecimal(number)));
                //订单分销价
                sceneOrder.setSharePrice(sceneTicket.getOrignPrice().multiply(new BigDecimal(number)));
                sceneOrder.setId(getUUID());
                //保存订单
                sceneOrderService.saveSceneOrder(sceneOrder);
                SceneOrderDetail orderDetail = new SceneOrderDetail();
                orderDetail.setModifyTime(new Date());
                orderDetail.setCreateTime(new Date());
                if (!ValidUtil.isEmpty(number)) {
                    orderDetail.setNumber(Integer.valueOf(number));
                }
                orderDetail.setPrice(sceneTicket.getPrice().subtract(discount));
                orderDetail.setSceneTricketId(sceneTicket.getId());
                orderDetail.setSceneOrderId(sceneOrder.getId());
                orderDetail.setId(getUUID());
                sceneOrderService.saveSceneOrderDetail(orderDetail);
                ajaxMsg.setDatas(sceneOrder);
            } catch (Exception e) {
                e.printStackTrace();
                ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
                ajaxMsg.setCode(AjaxMsg.FAILURE);
            }
        }else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setDatas(Constants.NOAUTH);
        }

        return ajaxMsg;
    }


    /**
     *
     * @param regionName 地点
     * @param pageSize 分页大小
     * @param pageNum 当前页数
     * @param orderType 排序类型
     * @param isDesc 升降序
     * @param category 类别
     * @param keyword 关键字
     * @return
     */
    @GetMapping(value = "/scenes/search")
    public AjaxMsg getSearch(String regionName,Integer pageSize, Integer pageNum,
                             String orderType,String isDesc,String category,String keyword) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map params = new HashMap();
        if (Constants.ORDER_PRICE.equals(orderType)) {
            //使用价格排序
            params.put("price", "price");
            if ("desc".equals(isDesc)) {
                params.put("isDesc", isDesc);
            }
        }
        Integer pageStart = (pageNum-1)*pageSize;
        params.put("pageStart", pageStart);
        params.put("pageSize", pageSize);
        params.put("sceneName", keyword);
        params.put("regionName", regionName);
        params.put("status",Constants. RES_STATUS_NORMAL);

        List<Map<String, Object>> scenes = sceneService.getBySearch(params);
        ajaxMsg.setDatas(scenes);
        return ajaxMsg;
    }
}
